// 电信投稿
$(function(){

    //读取用户信息
    getUser(); 
    
    

    //列表页：投票dom操作
    $('#tiles').on('click', '.toupiaoBtn', function () {
        let $par = $(this).closest('.itme-bottom');
        let $poll = $par.find('.poll');
        let num = Number($poll.html());
        let aid = $(this).attr('data-aid');       
        /*点击投票：
           0、判断cookie，如果有cookie，继续
                         如果无cookie，
           1、判断是否有标识，如果有标识，直接return false；
                            如果没有标识：就走接口
           2、接口：1）失败，弹出失败提示
                   2）成功：
                           [1]: 票数+1 ，添加标识
            
        */
        

       if( $(this).hasClass('voted')){
           toupiaoMsg('error','今天已经给他投过票啦!')
           return false;
       }
       else{               
            var url = `${baseUrl}api/articles/vote` ;  
            var data = {'aid':aid}
            $.ajax({
                url:url,
                type:'POST',
                dataType:"json",
                data:data,
                success:function(result){
                    var code = result.code;
                    var msg = result.msg;
                    var data = result.data;
                    
                    if(code == 100){     
                        clearUser();           
                        openLogin(); //未登录
                    }else if( code == 0){ 
                        //成功
                        $poll.html(++num);  
                        $(this).addClass('voted').html('已投票');                        
                        toupiaoMsg('success',msg);
                    
                    }else{
                        //失败
                        toupiaoMsg('error',msg);
                        
                    }
                }
        
            });
       }

       


    })

    //详情页：投票dom操作
    $('.detailContent').on('click', '.detailToupiaoBtn', function () {
        let $par = $(this).closest('.detailTitle');
        let $poll = $par.find('.voteNum');
        let num =  Number($poll.html());
        let aid = $(this).attr('data-aid');       
        /*点击投票：
           1、判断是否有标识，如果有标识，直接return false；
                            如果没有标识：就走接口
           2、接口：1）失败，弹出失败提示
                   2）成功：
                           [1]: 票数+1 ，添加标识
                      
        */
       if( $(this).hasClass('voted')){
           toupiaoMsg('error','今天已经给他投过票啦!')
           return false;
       }
       else{               
            var url = `${baseUrl}api/articles/vote` ;  
            var data = {'aid':aid}
            $.ajax({
                url:url,
                type:'POST',
                dataType:"json",
                data:data,
                success:function(result){
                    var code = result.code;
                    var msg = result.msg;
                    var data = result.data;
                    if(code == 100){                
                        openLogin(); //未登录
                    }else if( code == 0){ 
                        //成功
                        $poll.html(++num);  
                        $(this).addClass('voted').html('已投票');                        
                        toupiaoMsg('success',msg);
                    
                    }else{
                        //失败
                        toupiaoMsg('error',msg);
                        
                    }
                }
        
            });
       }

       


    })

    //展开
    $(".lookmore").on('click',function(){
        rule_open();
    })
    // 收缩规则
    $(".lookless").on('click',function(){
        rule_close();
    });

    
})

//base地址
var baseUrl = 'http://activity.chinatelecom.com.cn/';
// var baseUrl = 'http://36.112.130.16/';
var is_more = false;
var page = 1;


//按页数加载列表
let loadList = (page) =>{
    var url = `${baseUrl}api/articles?page=${page}` ;  
    $.get(url,function(result){
        let code = result.code;
        let msg = result.msg;
        let data = result.data;
        var boxHtml = '';  
        if(code == 0){
            let total = data.total;
            let limit = data.limit;
            let totalPage = total%limit==0 ? total/limit : Math.ceil(total/limit);
            console.log('加载了第:'+page +'页,数据总数:'+total + ',每页限制:'+ limit + ',totalPage:'+ totalPage);
            if(page > totalPage ){
                is_more = false;
                console.log('没有数据了~')
                page = totalPage;
                return false;
            }else{
                is_more = true;
                console.log('加载了第'+page+'页。')
                var articlesArr = data.articles;            
                articlesArr.forEach(el => {
                        var id = el.id;
                        var title = el.title;
                        var author = el.author;
                        var img = el.img;
                        var vote_num = el.vote_num;
                        boxHtml += `<li>
                            <div class="item">
                                <a href="detail.html?id=${id}" target="_blank">
                                    <img src="${baseUrl}${img}"/>
                                </a>
                                <div class="itme-bottom">
                                    <h3><i class="authorId">${id}.</i><a href="detail.html?id=${id}" target="_blank">${title}</a></h3>
                                    <p><i class="phoneHidden">作者：</i>${author} <span><i class="poll">${vote_num}</i>票</span></p>
                                    <button class="toupiaoBtn" data-aid="${id}">投票</button>
                                </div>
                            </div>
                        </li>`;
                });
            }                       
        }else{
            console.log('...')
        }      
        $('#tiles').append(boxHtml);    
        waterfall();        
    })    
}

//滚动加载列表
function onScroll(event) {
    // Check if we're within 100 pixels of the bottom edge of the broser window.
    var winHeight = window.innerHeight ? window.innerHeight : $(window).height(); // iphone fix
    var closeToBottom = ($(window).scrollTop() + winHeight > $(document).height() - 100);
    // console.log(winHeight,$(window).scrollTop(),closeToBottom);
    if (closeToBottom && is_more) {         
        setTimeout(function(){
            loadList(page++);          
        },300)   
        
        // console.log(page++);
    }else{       
        return false;
    }
};


//规则展开
var rule_open = () =>{
    $('.ruleContent').removeClass('limit');
} 

//规则收缩
var rule_close = () =>{    
    $('.ruleContent').addClass('limit');
    
} 


//加载文章方法
var loadArticle = (id)=>{

    var url = `${baseUrl}api/articles/read?id=${id}`;
    $.get(url,function(result){
    
        let code = result.code;
        let msg = result.msg;
        let data = result.data;
        if(code == 0){
            let title = data.title;
            let author = data.author;
            let img = data.img;
            let vote_num = data.vote_num; 
            let content = data.content;             
            
            var articeHtml = `<div class="detailTitle">
                    <h2>${title}</h2>
                    <p>作者：</i>${author}</span> <span><i>票数：</i><i class="voteNum">${vote_num}</i></span><button class="detailToupiaoBtn" data-aid="${id}">投票</button></p>
                </div>

                <div class="detail-acticle">
                    ${content}                    
                </div>`;
            $('.detailContent').empty().append(articeHtml);
        }else{
            let errorHtml=`<div class="errorBox"><i class="iconfont icon-wushuju"></i>暂无数据</div>`;
            $('.detailContent').empty().append(errorHtml);
        }

    });
   
   
}   

/*获取URL参数的函数*/
function getQueryString(name) {
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
    var r = window.location.search.substr(1).match(reg);
    if (r != null) {
        return unescape(r[2]);
    }
    return null;
}

//关闭弹出层
var closeTanchu = (id)=>{
    $('.coverbg').remove();
    $('#'+id).remove();
    $('body').removeClass('lock');
}

//弹出登录框
var openLogin =()=>{
    var loginHtml = `<div class="coverbg"></div>
                     <div class="loginContainer" id="loginContainer">
                        <h2>用户登录</h2>
                        <i class="iconfont icon-close closeLogin" onclick="closeTanchu('loginContainer')"></i>
                    
                        <div class="loginIpt">
                            <label for="tel">+86</label>
                            <input type="tel" class="ipt" maxlength="11" id="tel" placeholder="手机号" value="">
                            <input class="timeCount disabled" type="button" value="获取验证码" disabled onclick="sendMessage(this)">
                            <p id="error_tel"></p>
                        </div>
                        <div class="loginIpt">
                            <label for="verification">验证码</label>
                            <input type="text" class="ipt" id="verification" placeholder="验证码" maxlength="8">
                            <p id="error_ver"></p>
                        </div>
                        <button class="loginBtn disabled" disabled onclick="sendLogin()">登录</button>
                    </div>`;

    $('body').append(loginHtml);
    
    
    $("#tel").on('input',function(){
        var tel = $(this).val();
        if(isTel(tel)){
            $('.timeCount').removeClass('disabled').attr('disabled',false);
              
        }else{
            $('.timeCount').addClass('disabled').attr('disabled',true);              
        }
        loginbtnstatus(); //登录按钮状态判断
    })

    $('#verification').on('input',function(){
        var verNUm = $(this).val();
        if(verNUm == ''){
            $("#error_ver").html('');
        }
        loginbtnstatus(); //登录按钮状态判断

    })


}

//投票成功或失败
var toupiaoMsg = (type,text) =>{
    var toupiaoMsgHtml = `<div class="toupiao ${type}">
                            <i class="iconfont icon-${type}"></i><span>${text}</span>    
                       </div>`;
    

    if($('.toupiao').length >0){
        $('.toupiao').remove();
    }    
    $('body').append(toupiaoMsgHtml);

    setTimeout(function(){
        $('.toupiao').fadeOut();
    },2000);
}


//增加文章票数
var addpiaoNum = (aid) =>{
    var vote_num = $("#voteNum" + aid).html();
    vote_num = parseInt(vote_num);
    $("#voteNum" + aid).html(vote_num++);
    console.log('文章' + aid + ':' + vote_num +'票');
}

//瀑布流激活
let waterfall = ()=>{
    $('#tiles').imagesLoaded(function() {
            var handler = null;
            // Prepare layout options.
            var options = {
                autoResize: true, // This will auto-update the layout when the browser window is resized.
                container: $('#container'), // Optional, used for some extra CSS styling
                offset: 22, // Optional, the distance between grid items
                flexibleWidth: "25%",                
                itemWidth: itemWidth() // Optional, the width of a grid item
            };

             //通过宽度计算itemWidth
             function itemWidth(){
                let screenWidth = $(window).width();
                let width = parseInt((screenWidth/2)-35 );
                width = width < 200 ? width: 150;
                return width;
            }

            function applyLayout() {
                $('#tiles').imagesLoaded(function() {
                        // Destroy the old handler
                        if (handler.wookmarkInstance) {
                            handler.wookmarkInstance.clear();
                        }
                        
                        // Create a new layout handler.
                        handler = $('#tiles li');
                        handler.wookmark(options);
                });
            }

            /**
             * When scrolled all the way to the bottom, add more tiles.
             */
            function onScroll(event) {
                // Check if we're within 100 pixels of the bottom edge of the broser window.
                var winHeight = window.innerHeight ? window.innerHeight : $(window).height(); // iphone fix
                var closeToBottom = ($(window).scrollTop() + winHeight > $(document).height() - 100);

                if (closeToBottom) {
                    // Get the first then items from the grid, clone them, and add them to the bottom of the grid.
                    var items = $('#tiles li'),
                        firstTen = items.slice(0, 10);
                    $('#tiles').append(firstTen.clone());
                    applyLayout();
            }
            };

            // Capture scroll event.
            //$(window).bind('scroll', onScroll);

            // Call the layout function.
            handler = $('#tiles li');
            handler.wookmark(options);
    });
}

//获取token
var getToken = () =>{
    return new Promise((resolve, reject) => {
        var url = `${baseUrl}api/js.html`;    
        $.get(url,function(result){        
            console.log(result);        
            var str = result.split('=')[1];
            var token = str.substring(1,str.length-2);      
            // return token;   
            resolve(token);     
        }) 
    })

    
}


//60秒倒计时
var countdown  = 60;
var setTime = (el)=>{
    if(countdown == 0){
        el.removeAttribute('disabled');
        el.value = '重获验证码';
        countdown = 60;        
    }else{
        el.setAttribute('disabled',true);
        el.value = countdown + 's';
        countdown --;      
        setTimeout(function() {
            setTime(el)
        },1000)
    }
}

//手机号验证
var isTel = (tel)=>{
    var rtn = false;
    //电信手机号
    regtel = /^1[345789]\d{9}$/;
    if(regtel.test(tel)){
        rtn = true;
    }
    return rtn;
}

//验证码验证
var isVer = ( verNum ) =>{
    var rtn = false;
    regVer = /\d{6,8}/g; 
    if(regVer.test(verNum)){
        rtn = true;
    }
    return rtn;
}


//登录按钮状态判断
var loginbtnstatus = ()=>{
    var tel = $('#tel').val();
    var verNum = $('#verification').val();
    var $loginBtn = $('.loginBtn');
    if( isTel(tel) && isVer(verNum)){
        $loginBtn.removeClass('disabled').attr('disabled',false);
    }else{
        $loginBtn.addClass('disabled').attr('disabled',true);
    }   
}

//发送验证码
var trySend = ()=>{    
        var url = `${baseUrl}api/sms/send`;
        var data = {
            "tel":$('#tel').val(),
            // "__token__":token
        }

        $.ajax({
            type:'POST', 
            url:url,                       
            data:data,
            dataType:'json',
            success:function(result){
                var code = result.code;
                var msg = result.msg;
                var data =result.data;
                if(code == 1){
                    var errorHtml = `<span class="error"><i class="iconfont icon-jinggao"></i>${msg}</span>`;
                    $("#error_tel").html(errorHtml);
                }
                else if(code == 0){
                    var successHtml = `<span class="success"><i class="iconfont icon-success"></i>发送成功</span>`;
                    $("#error_tel").html(successHtml);
                    setTimeout(function(){  
                        $("#error_tel").html('');                        
                    },1500)
                }
            }            
        })      
}

//获取验证码：倒计时+发送s
var sendMessage =(el)=>{
    setTime(el);
    trySend();
    // getToken().then(function(data){
    //     console.log(data);
    //     trySend(data);
    // });
}


//登录
var sendLogin =()=>{
    var url = `${baseUrl}api/auth/login`;
    var tel = $('#tel').val();
    var data = {
        "tel":tel,
        "code":$('#verification').val()
    }
        
    $.ajax({
        type:'POST', 
        url:url,                       
        data:data,
        dataType:'json',
        success:function(result){
            let code = result.code;
            let msg = result.msg;
            let data = result.data;
            if(code == 0){
                //登录成功                               
                saveUser(tel); //将用户信息存在缓存里、并在头部插入html信息
                closeTanchu('loginContainer'); //关闭登录弹窗
            }
            else if(code == 1){
                //登录失败
                var errorHtml = `<span class="error"><i class="iconfont icon-jinggao"></i>${msg}</span>`;
                $('#error_ver').html(errorHtml);

            }
        }
        
    })
}

//将用户信息存在缓存里
var saveUser = (tel)=>{
    //设置一个2天的cookie
    $.cookie('loginphone', tel, { expires: 2, path: "/", domain: window.DomainName });
    
    var loginUpHtml = `<span>${tel}</span>
                       <a href="javascript:;" class="loginOut pr" onclick="logout()">退出</a>`;

    $('.user-info').empty().append(loginUpHtml);
}

//将用户信息清除
var clearUser = () =>{
    $.cookie('loginphone', '', { expires: -1 });
    var loginOutHtml = `<a href="javascript:;" class="loginIn pr" onclick="openLogin()">登录</a>`;
    $('.user-info').empty().append(loginOutHtml);

}

//读取用户信息
var getUser = () =>{
    var tel = $.cookie('loginphone');
    var loginUpHtml = `<span>${tel}</span>
                       <a href="javascript:;" class="loginOut pr" onclick="logout()">退出</a>`;
    var loginOutHtml = `<a href="javascript:;" class="loginIn pr" onclick="openLogin()">登录</a>`;

    var loginHtml = tel ? loginUpHtml:loginOutHtml;
    $('.user-info').empty().append(loginHtml);
}

//退出用户登录
var logout = () =>{
    var url = `${baseUrl}/api/auth/logout`;
    
    $.post(url,function(result){
            console.log(result);
            let code = result.code;
            let msg = result.msg;
            let data = result.data;
            if(code == 0){
                //退出成功                               
                clearUser();
            }
            
    })    
}